package self.hoy.demo.test.concurrent.cas;

import self.hoy.demo.cloud.order.lb.DemoLoadBalancer;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 在编写DemoLoadBalancer时发现 atomicInteger.getAndIncrement();
 * 此处对比/考察其线程安全
 * @author 三共小不
 * @date 2020/6/2
 */
public class IncreaseComparator {
    private void atomic(){
        final AtomicInteger atomicInteger = new AtomicInteger(0);
        for (int i = 0; i < 1000; i++) {
            new Thread() {
                public void run() {
                    for (int j = 0; j < 1000; j++) {
                        atomicInteger.getAndIncrement();
                        Thread.yield();
                    }
                }
            }.start();
        }
        System.out.println(atomicInteger.get());//999000, 997000, 998000, 998000, 996355, 997059, 996158
    }

    private void my(){
        final DemoLoadBalancer lb = new DemoLoadBalancer();
        for (int i = 0; i < 1000; i++) {
            new Thread() {
                public void run() {
                    for (int j = 0; j < 1000; j++) {
                        lb.getAndIncrement();
                        Thread.yield();
                    }
                }
            }.start();
        }
        //996237, 997049, 996567
        System.out.println(lb.get());
    }

    public static void main(String[] args) {
        new IncreaseComparator().my();
    }


}
